<template>
  <div class="home">
      标题：<input type="text" v-model="title">
      内容： <textarea id="" cols="30" rows="10" v-model="con"></textarea>

      <button @click="publish">{{this.id != -1 ? '修改' :'发表'}}</button>
  </div>
</template>

<script>
export default {
    data(){
        return {
            title:'',
            con:'',
            id:-1
        }
    },
    created(){
        
        //区分  添加还是要修改
        if(this.$route.query.id){
            //存在   修改
            this.id = this.$route.query.id;
            this.$http.get('/api/detail',{params:{id:this.id}}).then(res => {
                if(res.data.code === 1){
                    this.title = res.data.data.title;
                    this.con = res.data.data.con;
                }
            })
        }
    },
    methods:{
        publish(){
            if(this.title && this.con){
                //需要去判断是修改还是添加区别:1.接口地址  2.请求方式  put  post  3.id

                let url = this.id!= -1 ? '/api/edit' :'/api/add';

                let type = this.id!= -1 ? 'put' :'post';
                
                //发布接口
                this.$http[type](url,{id:this.id,title:this.title,con:this.con,author:localStorage.getItem('username')}).then(res => {
                    if(res.data.code === 1){
                       let msg =  this.id != -1 ? '修改成功' :'发布成功';
                       alert(msg);
                        this.$router.replace('/home');
                    }
                })
            }
        }
    }
}
</script>
